/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.aes.myinvoice;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * 
 * @author Raghav
 */
@WebService(serviceName = "MyInvoice")
public class MyInvoice {

	/**
	 * Web service operation
	 */
	@WebMethod(operationName = "getMyInvoice")
	public String getMyInvoice(@WebParam(name = "order") String order) {
		// TODO write your implementation code here:
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = null;
		try {
			dBuilder = dbFactory.newDocumentBuilder();
		} catch (ParserConfigurationException ex) {
			Logger.getLogger(MyInvoice.class.getName()).log(Level.SEVERE, null,
					ex);
		}
		Document doc = null;
		try {
			doc = dBuilder.parse(new ByteArrayInputStream(order.getBytes()));
		} catch (SAXException ex) {
			Logger.getLogger(MyInvoice.class.getName()).log(Level.SEVERE, null,
					ex);
		} catch (IOException ex) {
			Logger.getLogger(MyInvoice.class.getName()).log(Level.SEVERE, null,
					ex);
		}
		doc.getDocumentElement().normalize();

		double total = 0;
		NodeList myprice = doc.getElementsByTagName("UnitPrice");
		NodeList myqty = doc.getElementsByTagName("Quantity");
		try {
			for (int i = 0; i < myprice.getLength(); i++) {
				total += Double.parseDouble(myprice.item(i).getTextContent())
						* Integer.parseInt(myqty.item(i).getTextContent());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		Node root = doc.getElementsByTagName("CustomerOrder").item(0);
		Node totalNode = doc.createElement("TotalPrice");
		totalNode.setTextContent(Double.toString(total));
		root.appendChild(totalNode);
		String s = printXML(doc.getElementsByTagName("CustomerOrder").item(0));
		s.replace("CustomerOrder>", "Invoice>");
		return s;
	}

	private static String printXML(Node doc) {
		// set up a transformer
		TransformerFactory transfac = TransformerFactory.newInstance();
		Transformer trans = null;
		try {
			trans = transfac.newTransformer();
		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
		trans.setOutputProperty(OutputKeys.INDENT, "yes");

		// create string from xml tree
		StringWriter sw = new StringWriter();
		StreamResult result = new StreamResult(sw);
		DOMSource source = new DOMSource(doc);
		try {
			trans.transform(source, result);
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String xmlString = result.getWriter().toString();

		// print xml
		return xmlString;
	}

	/**
	 * Web service operation
	 */
	// @WebMethod(operationName = "please")
	// public String please(@WebParam(name = "me")
	// String me) {
	// //TODO write your implementation code here:
	// String s="<Invoice>";
	// s+=me;
	// s+="<TotalPrice>"+100.00+"</TotalPrice>";
	// s+="</Invoice>";
	// return s;
	// }

	/**
	 * Web service operation
	 */
	// @WebMethod(operationName = "getOrder")
	// public String getOrder(@WebParam(name = "order")
	// String order) throws ParserConfigurationException, SAXException,
	// IOException {
	// DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	// DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
	// Document doc = dBuilder.parse(new
	// ByteArrayInputStream(order.getBytes()));
	// doc.getDocumentElement().normalize();
	// String s="<Invoice>";
	// s+=order;
	// double total=0;
	// NodeList myprice = doc.getElementsByTagName("UnitPrice");
	// NodeList myqty = doc.getElementsByTagName("Quantity");
	// for(int i=0;i<myprice.getLength();i++){
	// total+=Double.parseDouble(myprice.item(i).getNodeValue())*Double.parseDouble(myqty.item(i).getNodeValue());
	// }
	// s+="<TotalPrice>"+total+"</TotalPrice>";
	// s+="</Invoice>";
	// return s;
	// }

}
